//
//  BBDataHelper.m
//  BBFoundation
//
//  Created by Gary on 5/4/16.
//  Copyright © 2016 Gary. All rights reserved.
//

#import "BBDataHelper.h"
#import "YTKKeyValueStore.h"

@implementation BBDataHelper

const YTKKeyValueStore *store;
+ (instancetype) shared {
    static dispatch_once_t once;
    static BBDataHelper *instance = nil;
    dispatch_once(&once, ^{
        instance = [[self alloc]initWithPath:@"YZHDB"];
    });
    return instance;
}


- (id)initWithPath:(NSString*)path{
    self = [super init];
    if (self) {
        store = [[YTKKeyValueStore alloc] initDBWithName:path];
    }
    return self;
}

/**
 *  保存／更新数据
 */
-(void) save:(id)object objId:(NSString *)objId {
    NSString *tabelName = NSStringFromClass([object class]);
    
    NSDictionary *dic;
    if (![object isKindOfClass:[NSDictionary class]]) {
        dic = [object mj_keyValues];
    } else {
        dic = object;
    }
    
    [store createTableWithName:tabelName];  //建表
    [store putObject:dic withId:objId intoTable:tabelName];  //将数据加入到表中
}

/**
 *  获取一个对象数据
 */
-(id) getObject:(NSString *)className objId:(NSString *)objId {
    NSDictionary *dic = [store getObjectById:objId fromTable:className];
    id object = [NSClassFromString(className)  mj_objectWithKeyValues:dic];
    return object;
}


/**
 *  获取所有数据
 */
-(NSArray *) getAll:(Class)aClass {
    return [store getAllItemsFromTable:NSStringFromClass(aClass)];
}

/**
 *  删除对应数据
 */
-(void) remove:(Class)aClass objId:(NSString *)objId {
    [store deleteObjectById:objId fromTable:NSStringFromClass(aClass)];
}

/**
 *  删除所有数据
 */
-(void) removeAll:(Class)aClass {
    [store clearTable:NSStringFromClass(aClass)];
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 *  保存更新用户登陆信息
 */
-(void) saveUser:(UserModel *)user {
//    [self signOut];
    [self saveUser:user logined:TRUE];
}

-(void) saveUser:(UserModel *)user logined:(BOOL)logined {
    user.logined = logined;
    
    if (user.logined == TRUE) {
    [self removeAll:[UserModel class]];
    }
    
    [self save:user objId:user.userId];
}

/**
 *  将当前账号转为备份状态
 */
-(void)backupCurrentUser {
    UserModel *user = [self getCurrentUserModel];
    if (!user) {
        return ;
    }
    user.backup = YES;
    
    [self saveUser:user logined:NO];
}

/**
 *  还原备份账号为当前登录状态用户
 */
-(void)restoreUser {
    NSArray *array = [self getAll:[UserModel class]];
    for (YTKKeyValueItem *item in array) {
        UserModel *user = [UserModel  mj_objectWithKeyValues:item.itemObject];
        if (user.backup) {
            user.backup = NO;
            [self saveUser:user];
            break ;
        }
    }
}

-(UserModel *)getCurrentBackupUser {
    NSArray *array = [self getAll:[UserModel class]];
    for (YTKKeyValueItem *item in array) {
        UserModel *user = [UserModel mj_objectWithKeyValues:item.itemObject];
        if (user.backup) {
            return user;
        }
    }
    return nil;
}

/**
 *  取消备份账号的备份状态
 */
-(void)cancelBackupUser {
    UserModel *user = [self getCurrentBackupUser];
    if (!user) {
        return ;
    }
    user.backup = NO;
    
    [self saveUser:user logined:NO];
}

/**
 *  获取用户登陆信息
 */
-(UserModel *) getUserWithId:(NSString *)userId {
    return [self getObject:NSStringFromClass([UserModel class]) objId:userId];
}
/**
 *  获取当前登录用户
 */
-(UserModel *) getCurrentUserModel {
    NSArray *array = [self getAll:[UserModel class]];
    for (YTKKeyValueItem *item in array) {
        UserModel *user = [UserModel  mj_objectWithKeyValues:item.itemObject];
        if (user.logined) {
            return user;
        }
    }
    return nil;
}
/**
 *  获取所有用户
 */
-(NSArray *) getAllUser {
    NSArray *array = [self getAll:[UserModel class]];
    NSMutableArray *users = [NSMutableArray array];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createdTime" ascending:NO];
    
    array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
    
    for (YTKKeyValueItem *item in array) {
        UserModel *user = [UserModel mj_objectWithKeyValues:item.itemObject];
        if (user) {
            [users addObject:user];
        }
    }
    return users;
}

/**
 *  删除当前用户
 */
-(void) removeCurrentUser {
    UserModel *user = [self getCurrentUserModel];
    [self remove:[UserModel class] objId:user.userId];
}
/**
 *  切换账号到下个账号
 *
 *  @return TRUE切换成功，FALSE切换失败
 */
-(BOOL) changeCurrentWithNextUser {
    NSArray *users = [self getAllUser];
    if (!users.count) {
        return FALSE;
    }
    UserModel *user = [users objectAtIndex:0];
    [self saveUser:user];
    return TRUE;
}

///**
// *  注销账号处理
// */
//-(void) signOut {
//    NSArray *array = [self getAll:[UserModel class]];
//    for (YTKKeyValueItem *item in array) {
//        UserModel *user = [UserModel  mj_objectWithKeyValues:item.itemObject];
//        if (user.logined) {
//            [self saveUser:user logined:FALSE];
//        }
//    }
//}

/**
 *  存储数据信息
 */
- (void)saveData:(id)data forKey:(NSString*)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:data forKey:key];
    [defaults synchronize];
}

- (id)getDataForKey:(NSString *)key {
    id object;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    object = [defaults objectForKey:key];
    return object;
}


@end
